package org.senseframework.support.example.mybatis.controller;

import org.senseframework.support.core.utils.JSONUtils;
import org.senseframework.support.example.mybatis.domain.User;
import org.senseframework.support.orm.mybatis.query.builder.DBBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by emeey on 2016/11/20.
 */
@Controller
@RequestMapping("/mybatis/user")
public class MybatisUserController {


    @ResponseBody
    @RequestMapping(value = {"/register"})
    public Object register() {
        // service 方式插入
//        userService.insert(InsertBuilder.build(User.class).set(user));
        // InsertBuilder直接插入
//        Mongo.build("a").eq("a",a).list(User.class);
        User user1 = new User();
        user1.setAccount("aaaa");
        user1.setAge(11);
        DBBuilder.build(User.class).set(user1).changeDatasource("sasa").save();
        return "user save success!";
    }

    @ResponseBody
    @RequestMapping(value = {"/update"})
    public Object update(User user) {
        // service 更新
//        userService.update(UpdateBuilder.build(User.class).set("nickname", user.getNickname()).set("age", user.getAge()).set("phone", user.getPhone()));
        // UpdateBuilder直接更新
        DBBuilder.build(User.class).eq("account", "234")
                .gt("age", 50)
                .set("nickname", user.getNickname())
                .set("age", user.getAge())
                .set("phone", user.getPhone()).update();
        return "user save success!";
    }

    @ResponseBody
    @RequestMapping(value = {"/list"})
    public Object list() {
        // QueryBuilder条件支持 or and 操作 where (a=#{a1} and b>#{b1}) or (a=#{a2} and b<#{b2})
        DBBuilder orBuilder = DBBuilder.build(User.class).eq("account", "123").gt("age", 0).or().eq("account", "234").gt("age", 18);
//        List list = userService.list(orBuilder);
        List list = orBuilder.list();
        return JSONUtils.toJSONString(list);
    }
}
